﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using global::TerhelesEloszto.Common;
using global::TerhelesEloszto.Engine;

namespace Presentation
{
	public partial class ModifyUser : System.Web.UI.Page
	{
		protected global::TerhelesEloszto.Engine.IEngine engine = global::TerhelesEloszto.Engine.Engine.Instance();
		IUser currentUser = null;
		protected void Page_Load( object sender, EventArgs e )
		{
			String visitorName = User.Identity.Name;
			if( !engine.IsAdmin( visitorName ) )
			{
				if( engine.IsTeacher( visitorName ) )
				{
					Response.Redirect( "~/Teacher/TeacherProblem.aspx" );
				}
				else
				{
					Response.Redirect( "~/Problem.aspx" );
				}

			}
			foreach( IAdmin actAdmin in engine.GetAdmins() )
			{
				if( actAdmin.Neptun.Equals( Request.QueryString["ID"] ) )
				{
					currentUser = actAdmin;
					break;
				}
			}
			if( currentUser == null )
			{
				foreach( ITeacher actTeacher in engine.GetTeachers() )
				{
					if( actTeacher.Neptun.Equals( Request.QueryString["ID"] ) )
					{
						currentUser = actTeacher;
						break;
					}
				}
			}
			if( currentUser != null && !Page.IsPostBack )
			{
				UserName.Text = currentUser.Name.Trim();
				EmailBox.Text = currentUser.Email.Trim();
			}
			else if( currentUser == null )
			{
				Response.Redirect( "~/Admin/User.aspx?msg=0" );
			}
		}



		protected void ModifySettings_Click( object sender, EventArgs e )
		{
			try
			{
				engine.UpdateUser( currentUser, UserName.Text, currentUser.PasswordHash, EmailBox.Text );
				Response.Redirect( "~/Admin/User.aspx?msg=1" );
			}
			catch( EngineException ex )
			{
				Response.Redirect( "~/Admin/User.aspx?msg=0" );
			}
		}

		protected void Resetpaswd_Click( object sender, EventArgs e )
		{
			try
			{
				engine.UpdateUser( currentUser, currentUser.Name, engine.CreateHash( currentUser.Neptun ), currentUser.Email );
				Response.Redirect( "~/Admin/User.aspx?msg=1" );
			}
			catch( EngineException ex )
			{
				Response.Redirect( "~/Admin/User.aspx?msg=0" );
			}
		}

	}
}